import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import AppLayout from '@/layout/AppLayout.vue'
import mediaRoutes from '@/router/modules/media'
import orderRoutes from '@/router/modules/order'
import premissionRoutes from '@/router/modules/premission'
import productRoutes from '@/router/modules/product'
import nprogeress from 'nprogress'
import 'nprogress/nprogress.css'
import { store } from '@/store'

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    component: AppLayout,
    meta: {
      title: '首页',
      requiresAuth: true
    },
    children: [
      {
        path: '',
        name: 'home',
        component: () => import('../views/home/index.vue')
      },
      mediaRoutes,
      orderRoutes,
      premissionRoutes,
      productRoutes
    ]
  },
  {
    path: '/login',
    component: () => import('../views/login/index.vue')
  }
]
const router = createRouter({
  history: createWebHashHistory(),
  routes
})
router.beforeEach((to, from) => {
  nprogeress.start() // 开启加载进度条
  // 而不是去检查每条路由记录
  // to.matched.some(record => record.meta.requiresAuth)
  if (to.meta.requiresAuth && !store.state.user) {
    // 此路由需要授权，请检查是否已登录
    // 如果没有，则重定向到登录页面
    return {
      path: '/login',
      // 保存我们所在的位置，以便以后再登录后跳转到之前的页面
      query: { redirect: to.fullPath }
    }
  }
})
router.afterEach(() => {
  nprogeress.done() // 结束加载进度条
})
export default router
